import uuid
from calendar import timegm
from datetime import datetime

from rest_framework_jwt.settings import api_settings


# 制作jwt payload
def jwt_payload_handler(sear, user):
    exp = datetime.now() + api_settings.JWT_EXPIRATION_DELTA
    header_img = user.header_img
    if header_img:
        request = sear.context.get('request', None)
        header_img = request.build_absolute_uri(header_img.url)
    else:
        if user.wx_user and user.wx_user.head_url:
            if "http://" in user.wx_user.head_url:
                header_img = user.wx_user.head_url.replace("http://", "https://")
            else:
                header_img = user.wx_user.head_url
        else:
            header_img = "https://oss.kalaibao.com/h5/default_header.png"
    payload = {
        'user_id': user.pk,
        'username': user.username,
        'exp': exp,
        'leader': user.leader.id if user.leader else "",
        'bank_card_no': user.bank_card_no if user.bank_card_no else "",
        "header_img": header_img,
        "user_code": user.user_code if user.user_code else "",
        "mobile": user.mobile,
        "bank": user.bank.name if user.bank else "",
        "name": user.name if user.name else user.mobile[0:3] + "*" * 4 + user.mobile[8:],
        "company_name":user.company.name if user.company else ""
    }
    if isinstance(user.pk, uuid.UUID):
        payload['user_id'] = str(user.pk)

    if api_settings.JWT_ALLOW_REFRESH:
        payload['orig_iat'] = timegm(
            datetime.utcnow().utctimetuple()
        )

    if api_settings.JWT_AUDIENCE is not None:
        payload['aud'] = api_settings.JWT_AUDIENCE

    if api_settings.JWT_ISSUER is not None:
        payload['iss'] = api_settings.JWT_ISSUER

    return payload
